package Proxy;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyHandler implements InvocationHandler {
    //porxy class(target interface implements class)
    private Object targetObj;

    /**
     * create dynamic proxy class
     * @param targetObj porxy target class
     * @return proxy class
     */
    public Object createProxy(Object targetObj) {
        this.targetObj = targetObj;
        return Proxy.newProxyInstance(targetObj.getClass().getClassLoader(), targetObj.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
        Object obj = null;
        try {
            before();
            obj = method.invoke(targetObj, objects);
            after();
        } catch (Exception e) {
            throw e;
        }

        return obj;
    }

    private void before() {
        System.out.println("before run");
    }

    private void after() {
        System.out.println("after run");
    }
}
